const app = getApp();
Page({//创建和编辑店铺
  data: {
    imgLists: [],
    thumb:[],
    uploadNum: 0,
    shebei: [
      { name: 'wifi', value: 'WIFI' },
      { name: 'stopc', value: '停车位'},
      { name: 'alipay', value: '支付宝付款' },
      { name: 'wxpay', value: '微信付款' },
    ],
    readonlys:true
  },
  onLoad: function (options) {
    
    this.setData({ query: options.id ? 'edit' : 'add', id: options.id ? options.id : 0, user: wx.getStorageSync('userinfo'), uid: parseInt(wx.getStorageSync('FXID')) });
    if (options.id) {
      this.setData({ pageval: '?id=' + options.id });
      var getdata = wx.getStorageSync('myshop');
      for (var k in getdata) {
        this.setData({ [k]: getdata[k] });
      }
      var sb = [];
      if (this.data.wifi) {
        sb.push('wifi');
      }
      if (this.data.stopc) {
        sb.push('stopc');
      }
      if (this.data.alipay) {
        sb.push('alipay');
      }
      if (this.data.wxpay) {
        sb.push('wxpay');
      }
      this.setData({ sb: sb });
    }
    
  },
  onReady: function () {

  },
  onShow: function () {
    if (app.reg()) {
      var pages = getCurrentPages();
      var currpage = pages[pages.length - 1];
      if (currpage.data.city) {
        this.setData({ cid: currpage.data.city.id, cname: currpage.data.city.text });
      }
      if (currpage.data.cat_info) {
        this.setData({ scid: currpage.data.cat_info.id, scname: currpage.data.cat_info.cname });
      }
    }  
  },
  checkboxChange:function(e){//value 是个数组 点一下存一个
    this.setData({ sb: e.detail.value});
  },
  onSub: function (e) {
    var yz = this.yanzen();
    if (yz && this.data.imgLists.length) {//当重新选择图片后，先上传图片在提交 否则直接提交
      this.uploadimg(this.data.imgLists);
    } else if(yz) {
      this.send('');
    }
  },
  upload: function () {
    wx.showLoading({ title: '打开相册中', mask: true });
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        wx.hideLoading();
        var arr = [];
        if (res.tempFilePaths.length == 1) {//只选了一张的时候
          arr.push(res.tempFilePaths[0]);
        } else if (res.tempFilePaths.length >= 2) {//选了多张
          arr = res.tempFilePaths;
        }
        
        var total = arr.length + that.data.imgLists.length + that.data.thumb.length;//判断总共有几张图片 最多9张

        if (total > 10) {//大于9张不能上传
          wx.showToast({
            title: '最多上传9张图片',
            icon: 'none'
          });
        } else {//设置选择的图片和数量
          arr.map(val => {
            that.data.imgLists.push(val);
          });//全部数组合并
          that.setData({
            imgLists: that.data.imgLists,
            uploadNum: total
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  uploadimg: function (data) {//开始上传
    var that = this, i = data.i ? data.i : 0, success = data.success ? data.success : 0, fail = data.fail ? data.fail : 0, p = 1, thumb = data.thumb ? data.thumb : [];
    if (this.data.upimg == 'ok') {
      that.send(thumb);
      return;
    }
    const uploadTask = wx.uploadFile({
      url: app.globalData.host + 'wechat/api/issue_upimg',
      filePath: data[i],
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data", 'X-Requested-With': 'XMLHttpRequest'
      },
      success: (res) => {
        var res_data = JSON.parse(res.data);
        if (res_data.state == 1) {
          thumb.push(res_data.data);
        }
        success++;
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        i++;
        if (i == data.length) { //当图片传完时，停止调用
          this.setData({ upimg: 'ok' });
          this.send(thumb);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          data.thumb = thumb;
          this.uploadimg(data);
        }
      }
    });
    uploadTask.onProgressUpdate((res) => {
      wx.showLoading({ title: '第 ' + (i + 1) + ' 张 ' + res.progress + ' %', mask: true });
    })
  },
  send: function (thumb) {//上传完毕正式提交
    if(thumb){//有值的时候，说明上传了，和之前上传过的合并
      thumb = thumb.concat(this.data.thumb);
    }else{//没上传，直接提交原有数据
      thumb = this.data.thumb.length ? this.data.thumb:'';
    }
    wx.showLoading({ title: '玩命发布中', mask: true });
    var header = this.data.header.replace(app.globalData.host.substring(0, app.globalData.host.length - 1), '');
    var data = {
      header: header, sname: this.data.sname, thumb: thumb,mobile:this.data.mobile,
      sb: this.data.sb, star_time: this.data.star_time,
      content: this.data.content,
      scid: this.data.scid, scname: this.data.scname,cid:this.data.cid,cname:this.data.cname,
      address: this.data.address, latitude: this.data.latitude, longitude: this.data.longitude, query: this.data.query
    };
    if(this.data.id){
      data['id'] = this.data.id;
    }
    wx.request({
      url: app.globalData.host + 'wechat/home/shop',
      data: data,
      method: 'POST',
      header: app.header(wx.getStorageSync('PHPSESSID')),
      success: d => {
        app.again(d.data.state);
        if (d.data.state == 1) {
          wx.hideLoading();
          wx.showModal({
            title:'操作成功',
            showCancel: false,
            content: '分享给朋友或者微信群，让更多的人知道您！',
            success: res => {
              wx.navigateBack({});
            }
          })             
        }else{
          wx.showToast({
            title: d.data.message, icon: 'none'
          })
        }    
      }
    })
  },
  onClose: function (e) {
    var index = e.currentTarget.id;
    this.data.imgLists.splice(index, 1);
    this.setData({
      imgLists: this.data.imgLists,
      uploadNum: this.data.imgLists.length + this.data.thumb.length
    });
  },
  onClosethumb: function (e) {
    var index = e.currentTarget.id;
    this.data.thumb.splice(index, 1);
    this.setData({
      thumb: this.data.thumb,
      uploadNum: this.data.imgLists.length + this.data.thumb.length
    });
  },
  upload_header:function(){
    wx.showLoading({ title: '打开相册中', mask: true });
    wx.chooseImage({
      sizeType: ['compressed'],
      count: 1,
      sourceType: ['album'],
      success:  (res)=> {
        wx.hideLoading();
        wx.showLoading({ title: '加载中', mask: true });
        var result = res.tempFilePaths[0];
        wx.uploadFile({
          url: app.globalData.host + 'wechat/api/issue_upimg',
          filePath: result,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data", 'X-Requested-With': 'XMLHttpRequest'
          },
          success: (res) => {
            var res_data = JSON.parse(res.data);
            if (res_data.state == 1) {
              this.setData({ header: app.globalData.host.substring(0, app.globalData.host.length - 1) + res_data.data});
            }else{
              wx.showToast({
                title: res_data.message,icon:'none'
              })
            }            
          },
          complete:function(){
            wx.hideLoading();
          }
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  onChange: function (e) {
    this.setData({ [e.currentTarget.dataset.name]: e.detail });
  },
  yanzen: function () {
    var say = "";
    if (!this.data.header) {
      say = "请上传头像";
    } else if (!this.data.sname) {
      say = "门店名不能为空";
    } else if (!this.data.address) {
      say = "地址不能为空";
    } else if (!this.data.star_time) {
      say = "营业时间不能为空";
    } else if (!this.data.content) {
      say = "店铺简介不能为空";
    } else if (!this.data.mobile) {
      say = "店铺电话不能为空";
    } else if (!this.data.cid) {
      say = "城市不能为空";
    } else if (!this.data.scid) {
      say = "分类不能为空";
    }
    if (say) {
      wx.showToast({ title: say, icon: 'none', mask: true });
      return false;
    }
    return true;
  },
  onMap: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.errMsg == 'chooseLocation:ok' && res.address) { 
          that.setData({ address: res.address, latitude: res.latitude, longitude: res.longitude, readonlys:false});          
        }
      },
      fail: res => {//用户拒绝，则提示重新获取
        this.setData({ dialogshow: true });     
      }
    })
  },
  onYx: function () {
    wx.openSetting({
      success: res2 => {
        if (res2.authSetting["scope.userLocation"]) {//如果用户重新同意了授权登录
          wx.showToast({ title: '授权成功', duration: 2000 });
          setTimeout(() => {  //要等2秒 才能收到数据
            this.onMap();
          }, 2000);
        }
      },
      fail: f => {
        console.log(f)
      }
    })
  },
  onYxno: function () {
    wx.showToast({
      title: '无法正常使用', icon: 'none'
    })
  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  }
})